//
//  PHAsset+RL.swift
//  RaveLand
//
//  Created by zhuxuhong on 2021/4/26.
//  Copyright © 2021 CSLY. All rights reserved.
//

import Photos
import BWToolKit


extension PHAsset {
    //TODO : 视频转换
    public func bw_convertToMp4(completion: BlockT<String?>?) {
        guard mediaType == .video else {
            return
        }
        
    }
    
    /// 获取`PHAsset`对应的`AVURLAsset`
    public func bw_fetchAVURLAsset(completion: BlockT<AVURLAsset>?) {
        let op = PHVideoRequestOptions()
        op.deliveryMode = .automatic
        op.version = .current
        PHImageManager.default().requestAVAsset(forVideo: self, options: op) { (avAsset, _, info) in
            guard let urlAsset = avAsset as? AVURLAsset else {
                debugPrint(info ?? "")
                return
            }
            completion?(urlAsset)
        }
    }
    
    /// 获取本地视频URL
    public func bw_fetchVideoURL(completion: BlockT<URL>?) {
        guard mediaType == .video else {
            return
        }
        bw_fetchAVURLAsset {
            completion?($0.url)
        }
    }
    
    /// 获取封面图
    public func bw_fetchImage(size: CGSize, completion: BlockT<UIImage>?) {
        let ops = PHImageRequestOptions()
        ops.resizeMode = .fast
        ops.isNetworkAccessAllowed = true
        PHImageManager.default().requestImage(for: self, targetSize: size, contentMode: .aspectFill, options: ops) { (img, info) in
            guard let img = img,
                  let degrade = info?[PHImageResultIsDegradedKey] as? Bool, !degrade,
                  info?[PHImageErrorKey] == nil
            else {
                debugPrint(info ?? "")
                return
            }
            completion?(img)
        }
    }
}
